/**
 * 处理书本接口的业务逻辑
 */
const getRandomInt = require('../utils')
const { createBookLocation, updateBookLocation, getBookLocation } = require('../service/location')
const { getBookInfo } = require('../service/book')

class LocationController {
  // 添加书本位置
  async addLocation(ctx, next) {
    const { book_id, shelf_number, aisle_number } = ctx.request.body

    // 编号为空
    if (!book_id || !shelf_number || !aisle_number) {
      ctx.body = {
        code: 500,
        msg: '编号不能为空'
      }
      return
    }

    // 书本不存在
    const book_exist = await getBookInfo({ book_id })
    if (book_exist.length === 0) {
      ctx.body = {
        code: 500,
        msg: '书本不存在'
      }
      return
    }

    // 书本已经有位置了
    const location_exist = await getBookLocation(book_id)
    if (location_exist.length !== 0) {
      ctx.body = {
        code: 500,
        msg: '该书本已有位置，请在下方修改'
      }
      return
    }

    const location_id = getRandomInt(1, 10000000)
    try {
      const res = await createBookLocation(location_id, book_id, shelf_number, aisle_number)
      ctx.body = {
        code: 200,
        msg: '添加书本位置成功',
        data: res
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '添加书本位置失败',
        error: error.message
      };
    }

  }

  // 修改书本位置
  async changeLocation(ctx, next) {
    const { book_id, shelf_number, aisle_number } = ctx.request.body
    const temp = await getBookLocation(book_id)
    if (!temp) {
      ctx.body = {
        code: 500,
        msg: '此图书不存在'
      };
    } else {
      try {
        if (book_id && shelf_number && aisle_number) {
          const res = await updateBookLocation(book_id, shelf_number, aisle_number)
          ctx.body = {
            code: 200,
            msg: '修改书本位置成功',
            data: res
          }
        } else {
          ctx.body = {
            code: 500,
            msg: '编号不能为空'
          }
        }
      }
      catch (error) {
        console.error(error);
        ctx.body = {
          code: 500,
          msg: '修改书本位置失败',
          error: error.message
        };
      }
    }

  }

  // 获取书本位置
  async getLocation(ctx, next) {
    const { book_id } = ctx.request.body;
    try {
      const res = await getBookLocation(book_id);
      if (res.length !== 0) {
        ctx.body = {
          code: 200,
          msg: '获取书本位置成功',
          data: res
        };
      } else {
        ctx.body = {
          code: 500,
          msg: '查找失败'
        };
      }
    }
    catch (error) {
      console.error(error);
      ctx.body = {
        code: 500,
        msg: '获取书本位置失败'
      };
    }
  }

}

module.exports = new LocationController()
